package com.ittsang.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ittsang.dto.ArticleDTO;
import com.ittsang.dto.PageDTO;
import com.ittsang.dto.R;
import com.ittsang.dto.UserDTO;
import com.ittsang.mapper.*;
import com.ittsang.pojo.Article;
import com.ittsang.pojo.UserClubPosts;
import com.ittsang.service.ArticleService;
import com.ittsang.utils.RedisConstants;
import com.ittsang.utils.RedisUtil;
import com.ittsang.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private ArticleCommentMapper articleCommentMapper;

    @Autowired
    private UserArticleLikeMapper userArticleLikeMapper;

    @Autowired
    private UserArticleCartMapper userArticleCartMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private UserClubPostsMapper userClubPostsMapper;

    @Autowired
    private UserMapper userMapper;

    // 分页缓存待添加

    @Override
    public R getArticle(PageDTO req) {
        //分页操作
        int pageNum = req.getPageNum();
        int pageSize = req.getPagesize();
        PageHelper.startPage(pageNum,pageSize);
        int skip= (pageNum-1)*pageSize;
        List<Article> articles = articleMapper.getArticle();
        for (Article article : articles) {
            int commentNum = articleCommentMapper.getArticleCommentNum(article.getId());
            article.setCommentNum(commentNum);
        }
        return setPage(pageNum, pageSize, skip, articles);
    }

    @Override
    public R getArticleByType(PageDTO req) {
        //分页操作
        int pageNum = req.getPageNum();
        int pageSize = req.getPagesize();
        PageHelper.startPage(pageNum,pageSize);
        int skip= (pageNum-1)*pageSize;
        List<Article> articles = articleMapper.getArticleByType(req.getArticleTypeId());
        return setPage(pageNum, pageSize, skip, articles);
    }

    private R setPage(int pageNum, int pageSize, int skip, List<Article> articles) {
        Page<Article> page = new Page<>(pageNum, pageSize);
        page.setTotal(articles.size());
        List<Article> articleDTOList = articles.stream().skip(skip)
                .limit(pageSize).collect(Collectors.toList());
        page.addAll(articleDTOList);
        return R.ok("查询成功").put("articles", page).put("total", page.getTotal());
    }

    @Override
    @Transactional
    public R getArticleInfoById(Integer articleId) {
        Article articles = articleMapper.getArticleInfoById(articleId);
        articleMapper.updateArticleReading(articleId);
        if (UserHolder.getUser() == null) {
            return R.ok("查询成功").put("articles", articles);
        }
        // 生成唯一key
        String key =  RedisConstants.HISTORY_USER_KEY + UserHolder.getUser().getId();
        UserDTO user = UserHolder.getUser();
        articles.setLike(userArticleLikeMapper.isLike(user.getId(), articleId));
        articles.setCart(userArticleCartMapper.isCart(user.getId(), articleId));
        redisUtil.lSet(key, String.valueOf(articleId), 60 * 60 * 24 * 7);
        return R.ok("查询成功").put("articles", articles);
    }

    @Override
    public R deletedArticleById(Integer articleId) {
       int num = articleMapper.deletedArticleById(articleId);
        return num > 0?R.ok("删除成功"):R.error("删除失败");
    }

    @Override
    public R alterArticleById(ArticleDTO articleDTO) {
        int num = articleMapper.alterArticleById(articleDTO);
        return num > 0?R.ok("修改成功"):R.error("修改失败");
    }

    @Override
    public R insertArticle(ArticleDTO articleDTO) {
        UserDTO user = UserHolder.getUser();
        if (user.getClubId() != 0) {
            articleDTO.setClubId(user.getClubId());
            articleDTO.setUserId(Math.toIntExact(user.getId()));
            int num = articleMapper.insertArticle(articleDTO);
            return num > 0?R.ok("添加成功"):R.error("添加失败");
        }
        articleDTO.setClubId(0);
        articleDTO.setUserId(Math.toIntExact(user.getId()));
        int num = articleMapper.insertArticle(articleDTO);
        return num > 0?R.ok("添加成功"):R.error("添加失败");
    }

    @Override
    public R bannedArticleById(Integer articleId) {
        int num = articleMapper.bannedArticleById(articleId);
        return num > 0?R.ok("成功"):R.error("失败");
    }

    @Override
    public R queryArticleTitle(PageDTO req) {
        //分页操作
        int pageNum = req.getPageNum();
        int pageSize = req.getPagesize();
        PageHelper.startPage(pageNum,pageSize);
        int skip= (pageNum-1)*pageSize;
        List<Article> articles = articleMapper.queryArticle(req.getTitle());
        for (Article article : articles) {
            int commentNum = articleCommentMapper.getArticleCommentNum(article.getId());
            article.setCommentNum(commentNum);
        }
        return setPage(pageNum, pageSize, skip, articles);
    }

    @Override
    public R getNotReviewedArticle(PageDTO pageDTO) {
        UserDTO user = UserHolder.getUser();
        UserClubPosts userRole = userClubPostsMapper.getUserRole(Math.toIntExact(user.getId()), user.getClubId());
        if (userRole == null) {
            return R.error("用户无权限");
        }
        List<Article> articles = articleMapper.getNotReviewedArtile(user.getClubId());
        int pageNum = pageDTO.getPageNum();
        int pageSize = pageDTO.getPagesize();
        PageHelper.startPage(pageNum,pageSize);
        int skip= (pageNum-1)*pageSize;
        return setPage(pageNum, pageSize, skip, articles);
    }

    @Override
    public R reviewedArticle(Integer articleId) {
        UserDTO user = UserHolder.getUser();
        UserClubPosts userRole = userClubPostsMapper.getUserRole(Math.toIntExact(user.getId()), user.getClubId());
        if (userRole == null) {
            return R.error("用户无权限");
        }
        boolean i = articleMapper.reviewedArticle(articleId, user.getId());
        return i ? R.ok("审核成功") : R.error("审核失败");
    }

    @Override
    @Transactional
    public R thumbsUp(Integer articleId) {
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return R.error("未登录");
        }
        int num = articleMapper.insertArticleLikeNum(articleId);
        int num1 = userArticleLikeMapper.insertLike(user.getId(), articleId);
        return num > 0 || num1 >0 ? R.ok("点赞成功") : R.error("点赞失败");
    }

    @Override
    public R unLike(Integer articleId) {
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return R.error("未登录");
        }
        int num = articleMapper.deletedArticleLikeNum(articleId);
        int num1 = userArticleLikeMapper.deletedLike(user.getId(), articleId);
        return num > 0 || num1 >0 ? R.ok("取消点赞") : R.error("取消点赞失败");
    }

    @Override
    public R collection(Integer articleId) {
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return R.error("未登录");
        }
        int num = articleMapper.insertArticleCartNum(articleId);
        int num1 = userArticleCartMapper.insertCart(user.getId(), articleId);
        return num > 0 || num1 >0 ? R.ok("收藏成功") : R.error("收藏失败");
    }

    @Override
    public R unFavorite(Integer articleId) {
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return R.error("未登录");
        }
        int num = articleMapper.deletedArticleCartNum(articleId);
        int num1 = userArticleCartMapper.deletedCart(user.getId(), articleId);
        return num > 0 || num1 >0 ? R.ok("取消收藏成功") : R.error("取消收藏失败");
    }

    @Override
    public R getUserArticle(PageDTO pageDTO) {
        UserDTO user = UserHolder.getUser();
        List<Article> articles = articleMapper.getUserArticle(user.getId());
        //分页操作
        int pageNum = pageDTO.getPageNum();
        int pageSize = pageDTO.getPagesize();
        PageHelper.startPage(pageNum,pageSize);
        int skip= (pageNum-1)*pageSize;
        return setPage(pageNum, pageSize, skip, articles);
    }

    @Override
    public R getUserCartArticle(PageDTO pageDTO) {
        List<Integer> i = userArticleCartMapper.getUserCartArticleId(UserHolder.getUser().getId());
        List<Article> articles = new ArrayList<>();
        for (Integer integer : i) {
            Article article = articleMapper.getArticleInfoById(integer);
            articles.add(article);
        }
        //分页操作
        int pageNum = pageDTO.getPageNum();
        int pageSize = pageDTO.getPagesize();
        PageHelper.startPage(pageNum,pageSize);
        int skip= (pageNum-1)*pageSize;
        return setPage(pageNum, pageSize, skip, articles);
    }

    @Override
    public R getUserLiketArticle(PageDTO pageDTO) {
        //分页操作
        int pageNum = pageDTO.getPageNum();
        int pageSize = pageDTO.getPagesize();
        PageHelper.startPage(pageNum,pageSize);
        int skip= (pageNum-1)*pageSize;

        List<Integer> i = userArticleLikeMapper.getUserLikeArticleId(UserHolder.getUser().getId());
        List<Article> articles = new ArrayList<>();
        for (Integer integer : i) {
            Article article = articleMapper.getArticleInfoById(integer);
            articles.add(article);
        }
        return setPage(pageNum, pageSize, skip, articles);
    }

    @Override
    public R unReviewedArticle(Integer articleId) {
        UserDTO user = UserHolder.getUser();
        UserClubPosts userRole = userClubPostsMapper.getUserRole(Math.toIntExact(user.getId()), user.getClubId());
        if (userRole == null) {
            return R.error("用户无权限");
        }
        boolean i = articleMapper.unReviewedArticle(articleId);
        return i ? R.ok("审核成功") : R.error("审核失败");
    }

    @Override
    public R getAuditArticle(PageDTO pageDTO) {
        UserDTO user = UserHolder.getUser();
        UserClubPosts userClubPosts = userClubPostsMapper.getUserRole(Math.toIntExact(user.getId()), user.getClubId());
        if (userClubPosts == null) {
            return R.error("用户无权限");
        }
        int pageNum = pageDTO.getPageNum();
        int pageSize = pageDTO.getPagesize();
        PageHelper.startPage(pageNum,pageSize);
        int skip= (pageNum-1)*pageSize;
        List<Article> articles = articleMapper.getAuditArticle(user.getClubId());
        for (Article article : articles) {
            article.setUserName(userMapper.getUserName(article.getUserId()));
        }
        return setPage(pageNum, pageSize, skip, articles);
    }

    @Override
    public R getUserRecordArticle(PageDTO pageDTO) {
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return R.error("用户未登录");
        }
        // 生成唯一key
        String key =  RedisConstants.HISTORY_USER_KEY + UserHolder.getUser().getId();
        long end = redisUtil.lGetListSize(key);
        List<Object> objects = redisUtil.lGet(key, 0, end);
        if (objects == null) {
            return R.ok("无历史记录");
        }
        Collections.reverse(objects);
        List<Object> collect = objects.stream().distinct().collect(Collectors.toList());
        List<Article> articles = new ArrayList<>();
        for (Object o : collect) {
            Article article = articleMapper.getArticleInfoById(Integer.parseInt(o.toString()));
            articles.add(article);
        }
        int pageNum = pageDTO.getPageNum();
        int pageSize = pageDTO.getPagesize();
        PageHelper.startPage(pageNum,pageSize);
        int skip= (pageNum-1)*pageSize;
        return setPage(pageNum, pageSize, skip, articles);
    }

    @Override
    public R deletedRecord() {
        String key =  RedisConstants.HISTORY_USER_KEY + UserHolder.getUser().getId();
        redisUtil.del(key);
        return R.ok("清除成功");
    }
}
